local DB = require("common.DB")
local LuaMongo = _G.lua_mongo
local Config = require("Config")

local function canDel(uuid)
	return type(uuid) == "string" and #uuid == 24 and not uuidInDb[uuid]
end

local function delChar()
	uuidInDb = {}
	LuaMongo.find(DB.db_char, nil, {lastLoginTime = 1, lastLogoutTime = 1})
	local tb = {}
	while true do
		if not LuaMongo.next(tb) then
			break
		end
		if uuidInDb[tb._id] then
			assert()
		end
		uuidInDb[tb._id] = math.max(tb.lastLoginTime, tb.lastLogoutTime)
	end
	local list = {}
	local listlen
	local query = {}
--char
	listlen = 0 --处理黑名单，敌人, family申请列表
	LuaMongo.find(DB.db_char, nil, {black = 1, blackLen = 1, enemy = 1, enemyLen = 1, helpUuid = 1, worship = 1, worshipLen = 1})
	while true do
		local tb = {}
		if not LuaMongo.next(tb) then
			break
		end
		
		local hasAdd
		for i = tb.blackLen -1, 0, -1 do
		    if not uuidInDb[tb.black[i].uuid] then
		       tb.black[i] = tb.black[tb.blackLen-1]
		       tb.black[tb.blackLen-1] = nil
		       tb.blackLen = tb.blackLen - 1
		       
		       if not hasAdd then
		          hasAdd = true
		          listlen = listlen + 1
		          list[listlen] = tb
		       end
		    end
		end
		for i = tb.enemyLen -1, 0, -1 do
        if not uuidInDb[tb.enemy[i].uuid] then
           tb.enemy[i] = tb.enemy[tb.enemyLen-1]
           tb.enemy[tb.enemyLen-1] = nil
           tb.enemyLen = tb.enemyLen - 1           
           if not hasAdd then
              hasAdd = true
              listlen = listlen + 1
              list[listlen] = tb
           end
        end
    end
    for i = tb.worshipLen -1, 0, -1 do
        if not uuidInDb[tb.worship[i].uuid] then
           tb.worship[i] = tb.worship[tb.worshipLen-1]
           tb.worship[tb.worshipLen-1] = nil
           tb.worshipLen = tb.worshipLen - 1           
           if not hasAdd then
              hasAdd = true
              listlen = listlen + 1
              list[listlen] = tb
           end
        end
    end    
	end
	for i = 1, listlen do
		query._id = list[i]._id
		list[i]._id = nil
		LuaMongo.update(DB.db_char, query, {["$set"] = list[i]})
	end
	print("delChar: modify", listlen)
end

local function delFamily()
--family 表
  local list = {}
  local listlen
  local query = {}
	listlen = 0
	LuaMongo.find(DB.db_family, nil, {memberList = 1, storeRecord = 1})  --处理成员和仓库记录表
	while true do
		local tb = {}
		if not LuaMongo.next(tb) then
			break
		end
		local hasAdd
		for _, v in ipairs(tb.memberList) do
			if canDel(v.uuid) then
				listlen = listlen + 1
				list[listlen] = tb._id
				hasAdd = true
				break
			end
		end
		
		if not hasAdd then
		    for _, v in ipairs(tb.storeRecord) do
		        if canDel(v.uuid) then
		            listlen = listlen + 1
                list[listlen] = tb._id    
                break   
		        end
		    end
		end
	end
	local removeCnt = 0
	local updateCnt = 0
	for i = 1, listlen do
		query._id = list[i]
		LuaMongo.find(DB.db_family, query, {memberList = 1, storeRecord = 1})
		local tb = {}
		if not LuaMongo.next(tb) then
			assert()
		end
		for i = #tb.storeRecord, 1, -1 do
		    local v = tb.storeRecord[i]
		    if canDel(v.uuid) then
		        tb.storeRecord[i] = tb.storeRecord[#tb.storeRecord]
		        tb.storeRecord[#tb.storeRecord] = nil
		    end
		end
		local tbMemberList = tb.memberList
		for k = #tbMemberList, 1, -1 do
			local v = tbMemberList[k]
			if canDel(v.uuid) then
				tbMemberList[k] = tbMemberList[#tbMemberList]
				tbMemberList[#tbMemberList] = nil
			end
		end
		local hasLeader
		for _, v in ipairs(tbMemberList) do
			if v.official == 1 then
				hasLeader = true
				break
			end
		end
		if hasLeader then
			tb._id = nil
			LuaMongo.update(DB.db_family, query, {["$set"] = tb})
			updateCnt = updateCnt + 1
		else
			LuaMongo.remove(DB.db_family, query)
			removeCnt = removeCnt + 1
		end
	end
	
	print("delFamily: listLen:", listlen, updateCnt, removeCnt)
end

local function delFriend() --好友表
--friend
  local list = {}
  local listlen
  local query = {}
  listlen = 0
	LuaMongo.find(DB.db_friend, nil, {uuid1 = 1, uuid2 = 1})
	while true do
		local tb = {}
		if not LuaMongo.next(tb) then
			break
		end
		if canDel(tb.uuid1) or canDel(tb.uuid2) then
			listlen = listlen + 1
			list[listlen] = tb._id
		end
	end
	for i = 1, listlen do
		query._id = list[i]
		LuaMongo.remove(DB.db_friend, query)
	end
	
	print("delFriend: listLen:", listlen)
end

local function delMail()
--mail
  local list = {}
  local listlen
  local query = {}
  listlen = 0
	LuaMongo.find(DB.db_mail, nil, {receiverUuid = 1})
	while true do
		local tb = {}
		if not LuaMongo.next(tb) then
			break
		end
		if not tb.receiverUuid or canDel(tb.receiverUuid) then
			listlen = listlen + 1
			list[listlen] = tb._id
		end
	end
	for i = 1, listlen do
		query._id = list[i]
		LuaMongo.remove(DB.db_mail, query)
	end
	
	print("delMail: listLen:", listlen)
end

local function delMarket()
--market
  local list = {}
  local listlen
  local query = {}
	listlen = 0
	LuaMongo.find(DB.db_market, nil, {send_id = 1})
	while true do
		local tb = {}
		if not LuaMongo.next(tb) then
			break
		end
		if canDel(tb.send_id) then
			listlen = listlen + 1
			list[listlen] = tb._id
		end
	end
	for i = 1, listlen do
		query._id = list[i]
		LuaMongo.remove(DB.db_market, query)
	end
	print("delMarket: listLen:", listlen)
end


local function getRank()
  UUID_IN_RANK = {}
  LuaMongo.find(DB.db_rank, nil, {uuid=1})
  while true do
    local tmp = {}
    if not LuaMongo.next(tmp) then
      break
    end
    UUID_IN_RANK[tmp.uuid] = 1
  end
end

local function delRole()
  getRank()
	LuaMongo.find(DB.db_char, nil, {lastLoginTime = 1, lastLogoutTime = 1, lv = 1, yuanbao = 1, rmb = 1})
	local list = {}
	while true do
		local data = {}
		if not LuaMongo.next(data) then
			break
		end
		if (not UUID_IN_RANK[data._id])
		  and data.lv < 35
			and data.middleFlag ~= 1
			and data.rmb == 0
			and data.yuanbao == 0
			and 30 * 24 * 3600 < _G.real_os_time() - math.max(data.lastLogoutTime, data.lastLoginTime)
			then list[#list + 1] = data._id
		end
	end
	local query = {}
	local cnt = 0
	for _, v in ipairs(list) do
		query._id = v
		LuaMongo.remove(DB.db_char, query)
		cnt = cnt + 1
	end
	print("del role cnt:", cnt)
	UUID_IN_RANK = nil
end

has_init = has_init or nil
function init()
  if has_init then return end
  has_init = true
	if Config.IS_WINDOWS ~= true then
		print("DelRoles")
		delRole()
		delChar()  --t_char表
		delFamily() --t_family表
		delFriend() --t_friend表
		delMail() -- t_mail表
		delMarket() --t_market表		
		uuidInDb = nil
	end
end
init()
